package com.yoo.module_base.utils

import android.os.Handler
import android.os.Looper
import android.os.Message
import java.util.*

/**
 * 定时器util
 */
class TimerUtil {
    private var mTimer: Timer? = null
    var isWorking = false
        private set
    private var isNeedStop = false
    private val mHandler: Handler? = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (!isNeedStop) {
                val listener = msg.obj as SDTimerListener
                listener.onWorkMain()
            }
        }
    }

    private fun sendRunMessage(listener: SDTimerListener) {
        val msg = mHandler!!.obtainMessage()
        msg.obj = listener
        msg.what = MESSAGE_WHAT
        mHandler.sendMessage(msg)
    }

    fun startWork(delay: Long, listener: SDTimerListener? = null) {
        newTimer().schedule(object : TimerTask() {
            override fun run() {
                listener?.apply {
                    onWork()
                    sendRunMessage(this)
                }
            }
        }, delay)
    }

    fun startWork(`when`: Date, listener: SDTimerListener? = null) {
        newTimer().schedule(object : TimerTask() {
            override fun run() {
                listener?.apply {
                    onWork()
                    sendRunMessage(this)
                }
            }
        }, `when`)
    }

    fun startWork(`when`: Date, period: Long, listener: SDTimerListener? = null) {
        newTimer().schedule(object : TimerTask() {
            override fun run() {
                listener?.apply {
                    onWork()
                    sendRunMessage(this)
                }
            }
        }, `when`, period)
    }

    fun startWork(delay: Long, period: Long, listener: SDTimerListener? = null) {
        newTimer().schedule(object : TimerTask() {
            override fun run() {
                listener?.apply {
                    onWork()
                    sendRunMessage(this)
                }
            }
        }, delay, period)
    }

    private fun newTimer(): Timer {
        stopWork()
        mTimer = Timer()
        isWorking = true
        isNeedStop = false
        return mTimer!!
    }

    fun stopWork() {
        isNeedStop = true
        mTimer?.cancel()
        mHandler?.removeMessages(MESSAGE_WHAT)
        isWorking = false
    }

    interface SDTimerListener {
        fun onWork()
        fun onWorkMain()
    }

    companion object {
        private const val MESSAGE_WHAT = 0
    }
}